﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Windows.Media;

namespace WTable
{
    public class Row : Panel
    {
        private double _maxChildDesiredHeight = 30;
        Pen pen = new Pen(Brushes.Black, 1);

        protected override void OnRender(DrawingContext dc)
        {
            base.OnRender(dc);
            dc.DrawLine(pen, new Point(0, RenderSize.Height - .5), new Point(RenderSize.Width, RenderSize.Height - .5));
        }

        //protected override Size MeasureOverride(Size constraint)
        //{
        //    foreach (var child in InternalChildren.OfType<Col>())
        //    {
        //        child.Margin = new Thickness(0, 0, 0, .5);
        //        child.Measure(new Size(30, 30));
        //        var dessize = child.DesiredSize;

        //        if (_maxChildDesiredHeight < dessize.Height)
        //        {
        //            _maxChildDesiredHeight = dessize.Height;
        //        }
        //    }
        //    var a = new Size(0, _maxChildDesiredHeight);
        //    return a;
        //    //return base.MeasureOverride(constraint);
        //}

        protected override Size MeasureOverride(Size availableSize)
        {
            var mySize = new Size();
            var childs = InternalChildren.OfType<Col>();
            var childMar = new Thickness(0, 0, 1, 1);
            foreach (var child in childs)
            {
                child.Margin = childMar;
                child.Measure(availableSize);
                mySize.Width += child.DesiredSize.Width;

                if (_maxChildDesiredHeight < child.DesiredSize.Height)
                {
                    _maxChildDesiredHeight = child.DesiredSize.Height;
                }
                mySize.Height = _maxChildDesiredHeight;
            }
            return mySize;
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            var cols = InternalChildren.OfType<Col>().ToList();
            //自定义宽度
            var ww = cols.Where(s => s.CWidth.IsAbsolute);
            double fenww = finalSize.Width - ww.ToList().Sum(s => s.CWidth.Value);
            var sw = cols.Where(s => s.CWidth.IsStar).ToList().Sum(s => s.CWidth.Value);
            double ItemWidth = fenww / sw;

            var rr = new Rect(0, 0, 0, _maxChildDesiredHeight);
            foreach (var item in cols)
            {
                if (item.CWidth.IsStar)
                    rr.Width = ItemWidth * item.CWidth.Value;
                else
                    rr.Width = item.CWidth.Value;
                item.Arrange(rr);
                rr.X += rr.Width;
            }

            return finalSize;

        }
    }

}
